import React, { Component } from 'react'
import {
    Card,
    Button,
    Table,
    message,
    Modal,
    Form,
    Input,
} from 'antd'

import {reqGetRoles, reqAddRoles, reqUpdateRole} from '../../api'
import AuthForm from './authForm/authForm'
import memoryUtils from '../../utils/memoryUtils'
import {formatGlobalDate} from '../../utils/dateUtils'

const {Item} = Form
// 角色路由import
export default class role extends Component {

    constructor (props) {
        super(props)
        // 表单的ref
        this.formItem = React.createRef()
        // 获取menus数据的ref
        this.formRef = React.createRef()
        this.state = {
            roles: [], // 角色列表
            role: {}, // 选中行的角色数据
            showModal: false, // 判断创建角色弹窗是否展示
            showAuth: false, // 判断权限弹窗是否展示
            loadingFlg: false, // 列表是否处于loading状态
            buttonDisabled: true,
            pageName: "角色管理",
        }
    }

    initColumn = () => {
        this.columns = [
            {
                title: '角色名称',
                dataIndex: 'roleName',
            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
                render: createTime => formatGlobalDate(createTime)
            },
            {
                title: '授权时间',
                dataIndex: 'authTime',
                render: authTime => authTime === null ? null : formatGlobalDate(authTime)
            },
            {
                title: '授权人',
                dataIndex: 'authName'
            },
        ]
    }

    // 选择行的回调函数
    onRow = role => {
        return {
            onClick: event => {
                this.setState({role})
            } // 点击行
        }

    }

    // 获取角色列表
    getRoles = async () => {
        const reponse = await reqGetRoles()
        const result = reponse.data
        if (result.status === 0) {
            this.setState({roles: result.data.roles, buttonDisabled: false})
        } else if (result.status === 2) {
            message.error("您没有使用" + this.state.pageName + "的权限")
        }else {
            message.error('获取用户权限信息失败')
        }
    }

    // 点击取消的回调函数
    handleCancel = () => {
        this.setState({showModal: false, showAuth: false})
    }

    // 添加角色的回调函数
    addRole = async () => {
        // 表单验证，通过了才继续
        await this.formItem.current.validateFields()
        // 获取input的值
        const roleName = this.formItem.current.getFieldsValue('createRole').createRole
        // 发送ajax请求前loading
        this.setState({loadingFlg: true})
        const reponse = await reqAddRoles(roleName)
        // 请求结束后取消loading
        this.setState({loadingFlg: false})
  
        const result = reponse.data
        if (result.status === 0) {
            message.success('添加角色信息成功')
            // 隐藏弹框
            this.setState({showModal: false})
            // react不建议直接更新数组，而是用原来的数组生成一个新的并更新
            // 在原来的基础上添加推荐使用函数更新state和原本的没有关系推荐对象更新state
            this.setState(state => (
                {roles: [...state.roles, result.data.role], role: result.data.role}
            ))
        } else {
          message.error(result.message)
        }
    }

    // 更新角色的回调函数
    updateRole = async () => {
        const role = this.state.role
        // 获取子组件选择的权限列表
        const menus = this.formRef.current.getMenus()
        // 除了要指定menus，还要制定权限赋予者
        role.menus = menus
        role.authName = memoryUtils.user.username
        const reponse = await reqUpdateRole(role)
        const result = reponse.data
        if (result.status === 0) {
            message.success('设置角色权限成功')
            this.setState({showAuth: false})
        } else {
            message.error(result.message)
        }
    }

    // 点击创建角色按钮的回调
    clickCreateRole = () => {
        // 设置100毫米的延迟，确保组件加载之后再清楚input框的值
        setTimeout(
            () => {
                this.formItem.current.setFieldsValue({
                    createRole: null
                })
            }, 100
        )
        this.setState({showModal: true})
    }

    componentWillMount () {
        this.initColumn()
    }

    componentDidMount () {
        this.getRoles()
    }

    render() {

        const {roles, role, showModal, loadingFlg, showAuth, buttonDisabled} = this.state
        const title = (
            <span>
                <Button type='primary' disabled={buttonDisabled} onClick={this.clickCreateRole}>创建角色</Button> &nbsp;
                <Button type='primary' disabled={(role.id) ? false : true} onClick={() => this.setState({showAuth: true})}>设置角色权限</Button>
            </span>
        )
        return (
            <div>
                <Card title={title}>
                    <Table
                        rowSelection={{type: 'radio', selectedRowKeys:[role.id]}}
                        rowKey="id"
                        bordered
                        dataSource={roles}
                        columns={this.columns}
                        loading={loadingFlg}
                        pagination={{defaultPageSize: '8', showQuickJumper: true}}
                        onRow={this.onRow}/>

                    {/* 创建角色 */}
                    <Modal title="创建角色"
                        visible={showModal}
                        onOk={this.addRole}
                        onCancel={this.handleCancel}
                        cancelText={'取消'}
                        okText={'确认'}>
                        <Form ref={this.formItem}>
                            <Item label="角色名称" name='createRole'  wrapperCol={{span: 14}} rules={[
                                {required: true, message: '角色名称不能为空!'}]}>
                                <Input placeholder={'请输入角色名'} allowClear={true} onPressEnter={this.updateCategory}></Input>
                            </Item>
                        </Form>
                    </Modal>

                    {/* 设置角色权限 */}
                    <Modal title="设置角色权限"
                        visible={showAuth}
                        onOk={this.updateRole}
                        onCancel={this.handleCancel}
                        cancelText={'取消'}
                        okText={'确认'}>
                            <AuthForm role={role} ref={this.formRef}/>
                    </Modal>
                </Card>
                {/* https://blog.csdn.net/chenqk_123/article/details/107781437
              https://blog.csdn.net/weixin_44956861/article/details/107344468?utm_term=antduseForm%E4%BD%BF%E7%94%A8&utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~sobaiduweb~default-0-107344468&spm=3001.4430
              表单和Model嵌套的时候表单无法通过自带的按钮进行验证
              hook组件使用const [form] = Form.useForm()引入form
              class组件yongref进行获取 this.formItem.current.validateFields() */}
            </div>
        )
    }
}
